package com.stedu.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import com.stedu.bean.Admin;
import com.stedu.bean.RespBean;
import com.stedu.service.AdminService;
import com.stedu.service.OwnerService;
import com.stedu.service.RepairerService;
import com.stedu.utils.JwtUtil;
import com.stedu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@CrossOrigin
@RestController
@RequestMapping
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private OwnerService ownerService;
    @Autowired
    private RepairerService repairerService;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/login")
    public RespBean login(@Validated String username, String password, String captchaId, String captcha) throws Exception {
        //判断验证码
        String captchaRedis = (String)redisUtil.get(captchaId);
        if (captchaRedis == null  || (captchaRedis != null && !captchaRedis.equalsIgnoreCase(captcha))) {
            return RespBean.error("验证码错误,请刷新");
        }
        //判断账号密码
        Admin admin = adminService.login(username, password);
        HashMap<String, Object> map = new HashMap<>();
        if (admin.getRole().equals("repairer")) {
            Integer rid = adminService.selectByUsername(username).getRid();
            map.put("id", rid);
        } else {
            map.put("id", admin.getId());
        }
        map.put("username", admin.getUsername());
        map.put("role", admin.getRole());
        String jwt = JwtUtil.generateJwt(map);
        return RespBean.ok("登陆成功",jwt);
    }

    //验证码
    @GetMapping("/captcha")
    public RespBean captcha() {
        //生成验证码对象
        LineCaptcha lineCaptcha = new LineCaptcha(120, 38, 4, 10);
        //获取验证码的文本
        String code = lineCaptcha.getCode();
        //生成唯一的ID
        String captchaId = UUID.randomUUID().toString().replace("-", "");
        //获取验证码文本保存在redis中
        redisUtil.set(captchaId, code, 60);
        //将captchaId和验证码图片发送给浏览器 Base64
        String captchaImageBase64Data = lineCaptcha.getImageBase64Data();
        HashMap<String, Object> map = new HashMap<>();
        map.put("captchaId", captchaId);
        map.put("captchaImageBase64Data", captchaImageBase64Data);
        return RespBean.ok("", map);
    }

}
